package com.syh.jn.scm.infrastructure.repository.utils;

import com.syh.jn.scm.infrastructure.support.SqlAdapter;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MybatisTemplate implements ApplicationContextAware {

  private static SqlSessionFactory mybatisSessionFactory;

  /**
   * mybatis 列表查询
   *
   * @param statement 查询方法所对应的命名空间.方法名
   * @param parameter 查询参数,可以为null
   * @param <E>
   * @return
   */
  public static <E> List<E> selectList(String statement, Object parameter) {
    SqlSession session = mybatisSessionFactory.openSession();
    List list = null;
    try {
      list = session.selectList(statement, parameter);
    } finally {
      session.close();
    }
    return list;
  }

  /**
   * mybatis 单个查询
   *
   * @param statement 查询方法所对应的命名空间.方法名
   * @param parameter 查询参数,可以为null
   * @param <T>
   * @return
   */
  public static <T> T selectOne(String statement, Object parameter) {
    List<T> objects = MybatisTemplate.<T>selectList(statement, parameter);
    return objects != null && objects.size() > 0 ? objects.get(0) : null;
  }

  public static <T> List<T> selectList(String sql) {
    return MybatisTemplate.<T>selectList("generalSql.generalSelect", new SqlAdapter(sql));
  }

  public static <T> T selectOne(String sql) {
    List<T> objects = MybatisTemplate.<T>selectList(sql);
    return objects != null && objects.size() > 0 ? objects.get(0) : null;
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    MybatisTemplate.mybatisSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
  }
}
